package com.bobi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bobi.entity.Member;
import com.bobi.entity.Promotion;
import com.bobi.enums.ResultCode;
import com.bobi.service.MemberService;
import com.bobi.utils.PageUtil;
import com.bobi.utils.ResultUtil;
import com.bobi.vo.PageVO;
import com.bobi.vo.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resources;
import java.util.List;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    //分页查询所有的数据
    //按名字查询，安按ID查询
    @GetMapping(value = "/page")
    public ResultMessage<Page<Member>> page(Member member, PageVO pageVO) {
        if(member == null){
            return ResultUtil.error(400015,"查询失败!!");
        }
        QueryWrapper<Member> queryWrapper = member.initWrapper(member);
        Page<Member> page = PageUtil.initPage(pageVO);
        Page<Member> list = new Page<>();
        if(queryWrapper == null){
            list = memberService.page(page);
        }else{
            list = memberService.page(page, queryWrapper);
        }
        return ResultUtil.data(list);
    }

    //添加会员
    @PostMapping
    public ResultMessage addMember(@RequestBody Member member) {
        // 如果添加成功
        if (memberService.save(member)) {
            return ResultUtil.success();
        }
        return ResultUtil.error(32013, "添加失败！");
    }

    //删除会员
    @DeleteMapping("/{id}")
    public ResultMessage  deleteMember(@PathVariable("id") String id){
        if(id == null){
            return ResultUtil.error(400014,"删除失败!");
        }
        memberService.removeById(id);
        return ResultUtil.success();
    }

    // 修改会员
    @PutMapping("/{id}")
    public ResultMessage updateMember(@PathVariable("id") String id, @RequestBody Member member) {
        // 构造查询条件包装
        UpdateWrapper<Member> updateWrapper = new UpdateWrapper<Member>().eq("id", id);
        // 如果更新成功
        if (memberService.update(member, updateWrapper)) {
            return ResultUtil.success();
        }
        return ResultUtil.error(40008, "更新失败！");
    }


    // // 删除全部函数
    @DeleteMapping("/all")
    public ResultMessage<Object>  deleteBatchActivity(@RequestParam List<String> ids){
        if(ids == null){
            return ResultUtil.error(400014,"删除全部失败！！");
        }
        memberService.removeBatchByIds(ids);
        return ResultUtil.success();
    }

}

